﻿
(function () {

    appModule.controller('tenant.views.manuscript.index', [
        '$scope', '$uibModal', 'uiGridConstants', 'appSession', 'abp.services.app.manuscript', 'abp.services.app.parameterType', 'abp.services.app.manuscriptStatus', 'abp.services.app.user',
        function ($scope, $modal, uiGridConstants, appSession, manuscriptService, parameterTypeService, manuscriptStatusService, userService) {
            var vm = this;

            $scope.$on('$viewContentLoaded', function () {
                Metronic.initAjax();
            });

            vm.loading = false;
            vm.filterText = null;
            vm.curManuscript = null;
            vm.permissions = {
                'create': abp.auth.hasPermission('Pages.Tenant.Manuscript.Create'),
                'edit': abp.auth.hasPermission('Pages.Tenant.Manuscript.Update'),
                'delete': abp.auth.hasPermission('Pages.Tenant.Manuscript.Delete'),
                'startAudit': abp.auth.hasPermission('Pages.Tenant.Manuscript.StartAudit'),//初稿审核权限
            };

            //编辑框输出转码
            htmlDecodeByRegExp = function (str) {
                var s = "";
                if (!str) return "";
                if (str.length == 0) return "";
                s = str.replace(/&amp;/g, "&");
                s = s.replace(/&lt;/g, "<");
                s = s.replace(/&gt;/g, ">");
                s = s.replace(/&nbsp;/g, " ");
                s = s.replace(/&#39;/g, "\'");
                s = s.replace(/&quot;/g, "\"");
                return s;
            }

            //获取类型
            parameterTypeService.getParameterTypes({}).success(function (result) {
                vm.ParameterTypes = result.items;
            }).finally(function () {

            });
            //获取稿件状态
            manuscriptStatusService.getManuscriptStatuss({}).success(function (result) {
                vm.ManuscriptStatus = result.items;
            }).finally(function () {

            });
            //获取主编用户
            userService.getEditor({ id: appSession.user.id }).success(function (result) {
                vm.EditorUser = result.items;
            }).finally(function () {

            });

            
            var urlManuscript = "/api/services/app/manuscript/";
            var fields = [];
            var table = [
                    {
                        title: 'ID',
                        field: 'id'
                    },
                    {
                        title: '稿件标题',
                        field: 'longTitle'
                    },
                    {
                        title: '作家',
                        field: 'fullName',
                        template: '#var str="";if(user!=null){str=user.fullName;}# #= str #'
                    },
                    {
                        title: '稿件类别',
                        field: 'manuscriptType',
                        template: '#var str="";if(manuscriptType!=null){str=manuscriptType.name;}# #=str#'
                    },
                    {
                        title: '栏目类别',
                        field: 'columnType',
                        template: '#var str="";if(columnType!=null){str=columnType.name;}# #=str#'
                    },
                    {
                        title: '投稿时间',
                        field: 'creationTime',
                        format: "{{dataItem.creationTime|date:'yyyy-MM-dd h:m:s'}}"
                    },
                    {
                        title: '稿件状态',
                        field: 'manuscriptStatu',
                        template: '#var str="";if(manuscriptStatu!=null){str=manuscriptStatu.manuscriptStatusName;}# #=str#'
                    },
                    {
                        title: '操作',
                        template: '<kendo-button ng-click="vm.openManuscriptChecked(dataItem);" ><span class="k-icon k-edit"></span> 转签审核</kendo-button>'
                    }
            ];
            //作家时的过滤条件和table页面
            if (appSession.user.isEditor == false) {
                fields = [{ field: "creatorUserId", operator: "eq", value: appSession.user.id }];
                table = [
                    {
                        title: 'ID ',
                        field: 'id'
                    },
                    {
                        title: '稿件标题 ',
                        field: 'longTitle'
                    },
                    {
                        title: '稿件类别 ',
                        field: 'manuscriptType',
                        template: '#var str="";if(manuscriptType!=null){str=manuscriptType.name;}# #=str#'
                    },
                    {
                        title: '栏目类别 ',
                        field: 'columnType',
                        template: '#var str="";if(columnType!=null){str=columnType.name;}# #=str#'
                    },
                    {
                        title: '投稿时间 ',
                        field: 'creationTime',
                        format: "{{dataItem.creationTime|date:'yyyy-MM-dd h:m:s'}}"
                    },
                    {
                        title: '稿件状态 ',
                        field: 'manuscriptStatu',
                        template: '#var str="";if(manuscriptStatu!=null){str=manuscriptStatu.manuscriptStatusName;}# #=str#'
                    }
                ];
            }
            //主编时的过滤条件
            if (appSession.user.isEditor == true) {
                if (vm.permissions.startAudit) {
                    fields = [
                        { field: "nextUserID", operator: "eq", value: appSession.user.id },
                        { field: "manuscriptStatu.order", operator: "eq", value: 1 }
                    ];
                } else {
                    fields = [
                        { field: "nextUserID", operator: "eq", value: appSession.user.id },
                        { field: "manuscriptStatu.order", operator: "eq", value: -1 }
                    ];
                }
            }
            var mainGridDataSource = new kendo.data.DataSource({
                type: 'aspnetmvc-ajax',
                transport: {
                    read: {
                        url: urlManuscript + "KendoGetManuscripts",
                        contentType: "application/json",
                        type: "POST"
                    },
                    parameterMap: function (options, operation) {
                        return JSON.stringify(options);
                    }
                },
                pageSize: 10,
                serverPaging: true,
                serverFiltering: true,
                serverSorting: true,
                schema: {
                    data: function (data) {
                        if (data.success === true && data.result != null) {
                            return data.result.data;
                        }
                        return {};
                    },
                    total: function (data) {
                        if (data.success === true && data.result != null) {
                            return data.result.total;
                        }
                        return 0;
                    },
                    model: {
                        id: "id",
                        fields: {
                            id: { type: "number" },
                        }
                    }
                },
                filter: {
                    logic: "and",
                    filters: fields
                }
            });
            vm.mainGridOptions = {
                dataSource: mainGridDataSource,
                columnMenu: true,
                reorderable: true,
                resizable: true,
                filterable: true,
                scrollable: true,
                selectable: "multiple",
                allowCopy: true,
                //height: 650,
                change: function (e) {
                    var selectedRows = this.select(); 2
                    for (var i = 0; i < selectedRows.length; i++) {
                        vm.curManuscript = this.dataItem(selectedRows[i]);
                    }
                },
                pageable: {
                    buttonCount: 5.0,
                    pageSize: 10,
                    pageSizes: [10, 20, 50, 100],
                    refresh: true
                },
                sortable: {
                    mode: "multiple"
                },
                messages: {
                    commands: {
                        excel: "导出"
                    }
                },
                columns: table,
                //detailTemplate:
                //    '<div><b>稿件标题:</b> #: longTitle #</div>' +
                //    '<div><b>投稿时间:</b> #: creationTime #</div>' +
                //    '<div><b>稿件类别:</b> #var str="";if(manuscriptType!=null){str=manuscriptType.name;}# #=str#</div>' +
                //    '<div><b>栏目类别:</b> #var str="";if(columnType!=null){str=columnType.name;}# #=str#</div>' +
                //    '<div><b>稿件状态:</b> #var str="";if(manuscriptStatu!=null){str=manuscriptStatu.manuscriptStatusName;}# #=str#</div>' +
                //    '<div><b>短标题:</b> #: shortTitle #</div>' +
                //    '<div><b>摘要:</b> #: summary #</div>' +
                //    '<div><b>关键词:</b> #: creationTime #</div>' +
                //    '<div><b>稿件描述:</b> #: manuscriptDescription #</div>' +
                //    '<div style="display:block;word-break: break-all;word-wrap: break-word;"><b>稿件内容:</b> #= htmlDecodeByRegExp(manuscriptContent) # </div>' +
                //    '<div>不显示？</div>' +
                //    '<div k-detail-template=""><div kendo-grid="" k-options="vm.auditGridOptions(dataItem)"></div></div>'
            };
            //审核意见列表
            vm.auditGridOptions = function (dataItem) {
                return {
                    dataSource: {
                        type: 'aspnetmvc-ajax',
                        transport: {
                            read: {
                                url: urlManuscript + "GetAudit?id="+dataItem.id ,
                                contentType: "application/json",
                                type: "POST"
                            },
                            parameterMap: function (options, operation) {
                                return JSON.stringify(options);
                            }
                        },
                        schema: {
                            data: function (data) {
                                if (data.success === true && data.result != null) {
                                    return data.result.items;
                                }
                                return {};
                            },
                            model: {
                                id: "id",
                                fields: {
                                    id: { type: "number" },
                                }
                            }
                        },
                       
                    },
                    //dataSource: [
                    //    { 'userId': '黄主编', 'auditContent': '有待加强啊', 'auditStatuId': '初审', 'creationTime': '2016.3.3' },
                    //    { 'userId': '刘主编', 'auditContent': '还不错的吧', 'auditStatuId': '审核中', 'creationTime': '2016.3.4' },
                    //    { 'userId': '谢主编', 'auditContent': '是非常不错的呀', 'auditStatuId': '终审', 'creationTime': '2016.3.5' },
                    //],
                    columnMenu: true,
                    reorderable: true,
                    resizable: true,
                    filterable: true,
                    scrollable: false,
                    //selectable: "multiple cell",
                    allowCopy: true,
                    pageable: false,
                    sortable: {
                        mode: "multiple"
                    },
                    columns: [
                    {
                        title: '审核主编',
                        field: 'user',
                        template:'#var str="";if(user!=null){str=user.fullName;}# #=str#'
                    },
                    {
                        title: '审核意见',
                        field: 'auditContent',
                    },
                    {
                        title: '审核状态',
                        field: 'auditStatu',
                        template: '#= auditStatu.manuscriptStatusName #'
                    },
                    {
                        title: '审核时间',
                        field: "creationTime",
                        format: "{{dataItem.creationTime|date:'yyyy-MM-dd h:m:s'}}"
                    }
                    ]
                };
            };




            //返回类型名称
            vm.returnTypesName = function (typesData, id) {
                var typesName = '未定义';
                for (var i = 0; i < typesData.length; i++) {
                    if (typesData[i].id == id) {
                        return typesData[i].name;
                    }
                }
                return typesName;
            };

            //返回状态名称
            vm.returnStatusName = function (statusData, id) {
                var statusName = '未定义';
                for (var i = 0; i < statusData.length; i++) {
                    if (statusData[i].id == id) {
                        return statusData[i].manuscriptStatusName;
                    }
                }
                return statusName;
            };
            function openCreateOreditManuscriptModal(manuscriptId) {
                var modalInstance = $modal.open({
                    templateUrl: '~/App/tenant/views/manuscript/createOrEditManuscript.cshtml',
                    controller: 'tenant.views.manuscript.createOrEditManuscript as vm',
                    backdrop: 'static',
                    resolve: {
                        manuscriptId: function () {
                            return manuscriptId;
                        },
                        parameterTypes: function () {
                            return vm.ParameterTypes;
                        }
                    }
                });

                modalInstance.result.then(function (result) {
                    vm.mainGridOptions.dataSource.read();
                });
            }
            vm.editManuscript = function () {
                if (vm.curManuscript) {
                    openCreateOreditManuscriptModal(vm.curManuscript.id);
                } else {
                    abp.message.error("请选择要修改的行!");
                }
            };

            vm.createManuscript = function () {
                openCreateOreditManuscriptModal(null);
            };

            vm.deleteManuscript = function () {
                if (vm.curManuscript != null && vm.curManuscript.id > 0) {
                    abp.message.confirm(
                        "是否要删除此条记录！",
                        function (isConfirmed) {
                            if (isConfirmed) {
                                manuscriptService.deleteManuscript({ id: vm.curManuscript.id }).success(function () {
                                    abp.notify.info(app.localize('SavedSuccessfully'));
                                    vm.mainGridOptions.dataSource.read();
                                }).finally(function () {

                                });
                            }
                        }
                    );
                } else {
                    abp.message.error("请选择要删除的行");
                }
            };
            //打开转签审核页面
            vm.openManuscriptChecked = function (datas) {
                var modalInstance = $modal.open({
                    templateUrl: '~/App/tenant/views/manuscript/manuscriptChecked.cshtml',
                    controller: 'tenant.views.manuscript.manuscriptChecked as vm',
                    backdrop: 'static',
                    resolve: {
                        manuscriptDatas: function () {
                            return datas;
                        },
                        manuscriptStatus: function () {
                            return vm.ManuscriptStatus;
                        },
                        editorUser: function () {
                            return vm.EditorUser;
                        }
                    }
                });

                modalInstance.result.then(function (result) {
                    vm.mainGridOptions.dataSource.read();
                });
            };

        }]);
})();
